﻿

using Utils.JobTask;

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;


namespace Microsoft.Extensions.DependencyInjection
{
    public static class JobServiceExtensions
    {

        public static IServiceCollection AddJob(this IServiceCollection services)
        {
            services.AddTransient(typeof(IJobService<>), typeof(JobService<>));
            return services.AddSingleton<IJobProvider, JobProvider>();
        }

    }

    public class JobTaskBuilder
    {
        internal Action<Exception> CallException { get; private set; }


        internal List<(Delegate @delegate, Cron cronExpression)> CronRunList { get; private set; } = new List<(Delegate, Cron)>();

        internal List<Delegate> InitedList { get; private set; } = new List<Delegate>();

        internal List<Type> RunServices { get; private set; } = new List<Type>();
        public JobTaskBuilder CatchException(Action<Exception> callException)
        {
            this.CallException = callException;
            return this;
        }
        /// <summary>
        /// 固定时间周期执行
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="init"></param>
        /// <param name="cronExpression">the cron expression to base the schedule on.</param>
        /// <returns></returns>
        public JobTaskBuilder Cron<T>(Action<T> init, string cronExpression)
        {
            try
            {
                CronRunList.Add((init, new Cron(cronExpression)));
            }
            catch
            {
                throw Error.SystemError("无效 cron 表达式");
            }
            return this;
        }

        public JobTaskBuilder Initing<T>(Action<T> init)
        {
            try
            {
                InitedList.Add(init);
            }
            catch
            {
                throw Error.SystemError("无效 cron 表达式");
            }
            return this;
        }
        public JobTaskBuilder AddService(Type type)
        {
            if (!RunServices.Contains(type))
                RunServices.Add(type);
            return this;
        }

        public JobTaskBuilder Use<T>()
        {
            AddService(typeof(T));
            return this;
        }
    }

}
